import { Component, OnInit } from '@angular/core';

import { CourseService } from 'src/app/services/course/course.service';
import { LocalStorageService } from 'src/app/services/local-storage/local-storage.service';
import { Course } from './interfaces/course.interface';

@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
  token: string;
  listOfBakData: Course[];
  listOfAllData: Course[];
  listOfDisplayData: Course[];
  isAllDisplayDataChecked = false; // 所有显示的数据是否全部选中
  isIndeterminate = false; // 是否为不确定状态
  mapOfCheckedId: { [key: string]: boolean } = {};

  constructor(
    private courseService: CourseService,
    private localStorage: LocalStorageService
  ) {}

  async ngOnInit() {
    this.token = this.localStorage.get('token');
    this.listOfAllData = (await this.courseService.getCourseData({
      token: this.token
    })) as Course[];
    this.listOfBakData = [...this.listOfAllData];
  }

  /**
   * 当前页面数据改变时，刷新表头复选框状态
   */
  currentPageDataChange($event: Course[]): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    // 如果所有显示的数据，都是选中的，则表头的复选框选中
    this.isAllDisplayDataChecked = this.listOfDisplayData.every(
      item => this.mapOfCheckedId[item.no]
    );
    // 如果所有显示的数据，至少有一个选中，并且不是全部选中，则表头复选框为不确定状态
    this.isIndeterminate =
      this.listOfDisplayData.some(item => this.mapOfCheckedId[item.no]) &&
      !this.isAllDisplayDataChecked;
  }

  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(
      item => (this.mapOfCheckedId[item.no] = value)
    );
    this.refreshStatus();
  }

  onSearched(courses: Course[]) {
    this.listOfAllData = courses;
  }
}
